﻿using System;
using System.Collections.Generic;
using chatGUI.DataBase.Entity;
using chatGUI.DataBase.Helper;


namespace chatGUI.DataBase.Dao;



public class GroupMemberDao{
    private static  readonly IFreeSql  fsql= SqlHelper.FSql;
    
    public static int Insert(GroupMember member){
        try {
            return fsql.Insert(member).ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }
        
        
    public static GroupMember Save(GroupMember gm){
        return fsql.GetRepository<GroupMember>().InsertOrUpdate(gm);
    }
    

    public static int DeleteById(string uid, string gid){
        try {
            return fsql.Select<GroupMember>().Where(g => g.Uid.Equals(uid) && g.Uid.Equals(gid)).ToDelete().ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }


    public static int InsertList(List<GroupMember> members){
        try {
            return fsql.Insert(members).ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }


    public static int DeleteAll(){
        try {
            return fsql.Select<GroupMember>().ToDelete().ExecuteAffrows();
        }
        catch (Exception) {
            return 0;
        }
    }

    /// <summary>
    /// 通过gid查询所有的群成员
    /// </summary>
    /// <param name="uid">uid不同查询到的备注不同</param>
    /// <param name="gid"></param>
    /// <returns></returns>
    public static List<FriendList> SelectUsers(string uid,string gid){

        List<string> members = fsql.Select<GroupMember>()
            .Where(f => f.Gid == gid)
            .ToList(g => g.Uid);
        List<FriendList> users = new List<FriendList>();
        foreach (var member in members) {
            var user = FriendDao.SelectById(uid,member);
            if (user == null) {
                users.Add(new FriendList{Uid = null, Fid = member});
            }
            else {
                users.Add(user);
            }
        }
        return users;
    }
        
    /// <summary>
    /// 查询一个用户加入的所有群
    /// </summary>
    /// <param name="uid"></param>
    /// <returns></returns>
    public static List<Group> SelectGroups(string uid){
        var groups = fsql.Select<GroupMember, Group>()
            .Where((m, g) => m.Uid.Equals(uid) && m.Gid.Equals(g.Gid) && m.Gid == g.Gid)
            .ToList((m,g)=>g);
        return groups;
    }
}

